#include <iostream>
#include <string>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

static void Usage(const std::string& proc) {
    std::cout << "\n\tUsage: " << proc << " serverip serverport\n" << std::endl;
}

int main(int argc, char* argv[]) {
    if (argc != 3) {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);    
    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip, serverport);
    if (!r) return 1;

    srand(time(nullptr) ^ getpid());
    int cnt = 1;
    const std::string opers = "+-*/%=-=&^";
    std::string inbuff_stream;//报文
    while (cnt <= 10) {
        std::cout << "第" << cnt << "次测试" << std::endl;
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(1234);
        char op = opers[rand() % opers.size()];
        Request req(x, y, op);//初始化请求
        req.DebugPrint();

        std::string package;
        req.Serialize(&package);
        package = Encode(package);
        std::cout << "最新发出的请求：\n" << package;
        write(sockfd.Fd(), package.c_str(), package.size());
        // write(sockfd.Fd(), package.c_str(), package.size());
        // write(sockfd.Fd(), package.c_str(), package.size());
        // write(sockfd.Fd(), package.c_str(), package.size());

        char buffer[128];
        int n = read(sockfd.Fd(), buffer, sizeof(buffer));
        if (n > 0) {
            buffer[n] = 0;
            inbuff_stream += buffer;//报文
            std::cout << inbuff_stream << std::endl;
            
            std::string content;//有效载荷
            bool r = Decode(inbuff_stream, &content);
            assert(r);

            Response resp;
            r = resp.Deserialize(content);
            assert(r);

            resp.DebugPrint();
            cnt++;
        }
        // usleep(500000);
        sleep(1);
    }

    sockfd.Close();
    return 0;
}